package com.wj.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wj.service.IUserInfoService;
import com.wj.service.IUserService;
import com.wj.utils.ContextUtil;
import com.wj.utils.RespBean;
import com.wj.utils.UserUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author wj
 * @Date 2022/5/30 16:20
 * @Description: TODO 一次的请求过滤器
 * @Version 1.0
 */
public class LoginAfterFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest resq, HttpServletResponse resp, FilterChain filterChain) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        IUserService userService = ContextUtil.getBean(IUserService.class);

        //登录以后却被禁用的
        if (SecurityContextHolder.getContext().getAuthentication()!=null &&
                !userService.getById(UserUtil.getCurrentUser().getId()).getIsEnable()){
            String successRes = new ObjectMapper().writeValueAsString(RespBean.error("账号已被禁用，请联系管理员"));
            resp.getWriter().print(successRes);
            return;
        }

        filterChain.doFilter(resq, resp);
    }

    //
    @Override
    protected void doFilterNestedErrorDispatch(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        super.doFilterNestedErrorDispatch(request, response, filterChain);
    }
}
